package net.tngou.db.netty;

import java.net.InetAddress;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

import net.tngou.db.query.Query;
import net.tngou.db.util.ResultSet;
import net.tngou.db.util.SerializationUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


public class ServerHandler extends SimpleChannelInboundHandler<byte[]>{

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, byte[] msg)
			throws Exception {
		// Generate and write a response.
	
		ResultSet response= (ResultSet) SerializationUtils.deserialize(msg);
		if(!response.getMsg().startsWith("exit"))
		{
			Query query = new Query();
			response=query.sql(response.getMsg());
		}
		 ctx.writeAndFlush(SerializationUtils.serialize(response));
//		// Close the connection after sending 'Have a good day!'
//		// if the client has sent 'bye'.
//		if (close) {
//			future.addListener(ChannelFutureListener.CLOSE);
//		}

		
	}
	
	
	 
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}
	

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}

}
